//
//  JourneyWayPointsViewController.m
//  Travel_M_Travel
//
//  Created by APPLE10 on 15-4-1.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "JourneyWayPointsViewController.h"
#import "WayPointHeaderView.h"
#import "JourneryNetHandler.h"
#import "WayPointDataSource.h"
#import "WayPointCollectionViewCell.h"
#import "WayPointDataSource_WayPoints.h"
#import "UIColor+AddColor.h"
#import "SDWebImageManager.h"
#import "MBProgressHUD.h"
#import "PhotoWallCollectionViewCell.h"
#import "JourneyPhotoDataSource.h"

@interface JourneyWayPointsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, MBProgressHUDDelegate>

@property (nonatomic , retain)UICollectionView *wayPointCV;
@property (nonatomic , retain)NSMutableArray *wayPointArr;
@property (nonatomic , retain)WayPointHeaderView *wayPointHeader;

@property (nonatomic , retain)UIImageView *userImagev;
@property (nonatomic , retain)UILabel *yearLable;
@property (nonatomic , retain)UILabel *titleLable;
@property (nonatomic , retain)UILabel *lineLable;

@property (nonatomic , retain)MBProgressHUD *progress;

@property (nonatomic , retain)UICollectionView *photoCV ;
@property (nonatomic , retain)NSMutableArray *photoArr;

@property (nonatomic , retain)UIView *userView;

@end

@implementation JourneyWayPointsViewController

-(void)dealloc
{
    [_wayPointCV release];
    [_wayPointArr release];
    [_wayPointHeader release];
    [_userImagev release];
    [_yearLable release];
    [_titleLable release];
    [_lineLable release];
    [_progress release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self netHandler];
    
    [self addPhotoCollectionView];
    
    [self addViewHeader];
    
    [self addCollectionView];
    
}

- (void)backBtuAction:(UIButton *)btu
{
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)addViewHeader
{
    CGFloat selfWidth = self.view.frame.size.width;
    //    CGFloat selfHight = self.view.frame.size.height;
    
    self.userView = [[UIView alloc]initWithFrame:CGRectMake(0,10, self.view.frame.size.width, 80)];
    _userView.backgroundColor =[UIColor whiteColor];
    
    //    UIButton *backBtu = [UIButton buttonWithTitle:@"返回" frame:CGRectMake(self.view.frame.size.width - 80, 0, 80, 80) target:self action:@selector(backBtuAction:)];
    //    backBtu.backgroundColor = [UIColor lightGrayColor];
    //    [_userView addSubview:backBtu];
    //用户头像
    self.userImagev = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10,  60  , 60 )];
    _userImagev.clipsToBounds = YES;
    _userImagev.layer.cornerRadius = 30;
    //    _userImagev.backgroundColor = [UIColor redColor];
    [_userView addSubview:_userImagev];
    [_userImagev release];
    
    //标题
    self.titleLable = [[UILabel alloc]initWithFrame:CGRectMake(70,0, selfWidth, 60 *3 /4)];
    _titleLable.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:17];
    //    _titleLable.backgroundColor = [UIColor redColor];
    [_userView addSubview:_titleLable];
    [_titleLable release];
    
    //时间
    self.yearLable = [[UILabel alloc]initWithFrame:CGRectMake(70,60 *3/ 4, selfWidth, 60/ 4)];
    _yearLable.font = [UIFont fontWithName:@"helvetica" size:10];
    //    _yearLable.backgroundColor = [UIColor yellowColor];
    [_userView addSubview:_yearLable];
    [_yearLable release];
    
    //查看线路日程
    self.lineLable = [[UILabel alloc]initWithFrame:CGRectMake(70, 60, selfWidth, 20)];
    //    _lineLable.textAlignment = NSTextAlignmentCenter;
    //    _lineLable.backgroundColor = [UIColor colorFromHexCode:@"#A1A1A1"];
    _lineLable.font = [UIFont fontWithName:@"Georgia" size:15];
    _lineLable.text = @"查看线路日程";
    //    _lineLable.backgroundColor =[UIColor greenColor];
    [_userView addSubview:_lineLable];
    [_lineLable release];
    
}

- (void)addCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
    
    //最小列间距
    flowLayout.minimumInteritemSpacing = 0;
    //最小行间距
    flowLayout.minimumLineSpacing = 0;
    //边缘距离
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    //设置头部并给定大小
    [flowLayout setHeaderReferenceSize:CGSizeMake(_wayPointCV.frame.size.width, 35)];
    
    
    self.wayPointCV = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 90, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flowLayout];
    _wayPointCV.backgroundColor = [UIColor whiteColor];
    _wayPointCV.delegate = self;
    _wayPointCV.dataSource = self;
    
    
    //cell 注册
    [_wayPointCV registerClass:[WayPointCollectionViewCell class] forCellWithReuseIdentifier:@"footPoint"];
    
    //头部视图注册
    [_wayPointCV registerClass:[WayPointHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"wayHeader"];
    
    [self.view addSubview:_wayPointCV];
    
    self.progress = [[MBProgressHUD showHUDAddedTo:self.view animated:YES]retain];
    [_progress show:YES];
    self.progress.delegate = self;
    
    
    [flowLayout release];
    [_wayPointCV release];
}

- (void)addPhotoCollectionView
{
    UICollectionViewFlowLayout *photoflowLayout = [[UICollectionViewFlowLayout alloc]init];
    photoflowLayout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
    //最小列间距
    photoflowLayout.minimumInteritemSpacing = 0;
    //最小行间距
    photoflowLayout.minimumLineSpacing = 0;
    //边缘距离
    photoflowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //滚动方向
    photoflowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    
    
    self.photoCV = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:photoflowLayout];
    _photoCV.backgroundColor = [UIColor blackColor];
    //按页滚动
    _photoCV.pagingEnabled = YES;
    _photoCV.delegate = self;
    _photoCV.dataSource = self;
    
    
    //注册cell
    [_photoCV registerClass:[PhotoWallCollectionViewCell class] forCellWithReuseIdentifier:@"照片"];
    
    [self.view addSubview:_photoCV];
    
    [photoflowLayout release];
    [_photoCV release];
}


//添加头部视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.wayPointCV) {
        UICollectionReusableView *resuableView = nil;
        self.wayPointHeader = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"wayHeader" forIndexPath:indexPath];
        
        WayPointDataSource *wayData = [_wayPointArr objectAtIndex:indexPath.section];
        
        _wayPointHeader.wayData = wayData;
        
        resuableView = _wayPointHeader;
        return resuableView;
        
    }else
    {
        return nil;
    }
    
}

- (void)netHandler
{
    NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/?target_type=%@&target_id=%@",self.idNumber,self.target_type,self.target_id];
    NSLog(@"%@",str);
    [JourneryNetHandler getDataWithUrl:str completion:^(NSDictionary *resultDic) {
        
        NSArray *arr = [resultDic objectForKey:@"days"];
        
        NSString *userStr = [[resultDic objectForKey:@"user"] valueForKey:@"avatar_l"];
        
        [self.userImagev setImageWithURL:[NSURL URLWithString:[[userStr stringByRemovingPercentEncoding] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[UIImage imageNamed:@"jiazai1.png"]];
        
        self.titleLable.text =[resultDic objectForKey:@"name"];
        
        NSString *dayStr = [NSString stringWithFormat:@"%@",[resultDic objectForKey:@"day_count"]];
        self.yearLable.text = [[[[resultDic objectForKey:@"first_day"] stringByAppendingString:@" | "]stringByAppendingString:dayStr]stringByAppendingString:@"天"] ;
        
        
        
        self.wayPointArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in arr) {
            
            WayPointDataSource *wayData = [[WayPointDataSource alloc]initWithDictionary:dic];
            
            NSMutableArray *dataArray = [dic objectForKey:@"waypoints"];
            
            NSMutableArray *secArr = [NSMutableArray array];
            for (NSMutableDictionary *dic in dataArray) {
                
                WayPointDataSource_WayPoints *data = [[WayPointDataSource_WayPoints alloc]initWithDictionary:dic];
                [secArr addObject:data];
                
                
                [data release];
                
            }
            wayData.waypoints = secArr;
            
            [self.wayPointArr addObject:wayData];
            
            [wayData release];
        }
        
        [self.wayPointCV reloadData];
        [self.photoCV reloadData];
        [self.view addSubview:_userView];
        [_progress hide:YES];
    }];
    
}

#pragma mark collectionView deleget

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (collectionView == self.wayPointCV) {
        if (self.wayPointArr.count == 0) {
            return 0;
        } else {
            return [self.wayPointArr count];
        }
    }else
    {
        if (self.wayPointArr.count == 0) {
            return 0;
        } else {
            return [self.wayPointArr count];
        }
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.wayPointCV) {
        if (self.wayPointArr.count ==0) {
            return 0;
        } else {
            
            return [[[self.wayPointArr objectAtIndex:section] waypoints] count];
        }
    }else
    {
        if (self.wayPointArr.count ==0) {
            return 0;
        } else {
            
            return [[[self.wayPointArr objectAtIndex:section] waypoints] count];
        }
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.wayPointCV) {
        WayPointCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"footPoint" forIndexPath:indexPath];
        WayPointDataSource *wayData = _wayPointArr[indexPath.section];
        WayPointDataSource_WayPoints *data = wayData.waypoints[indexPath.item];
        cell.wayPointData_wayPoint = data;
        
        [cell setBlock:^{
            [self.view bringSubviewToFront:_photoCV];
            [self.photoCV scrollToItemAtIndexPath:indexPath atScrollPosition:(UICollectionViewScrollPositionNone)  animated:NO];
        }];
        return cell;
    }else
    {
        PhotoWallCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"照片" forIndexPath:indexPath];
        WayPointDataSource *wayData = _wayPointArr[indexPath.section];
        WayPointDataSource_WayPoints *data = wayData.waypoints[indexPath.item];
        cell.wayPointData_way = data;
        cell.mode = PhotosCVCellModeMax;
        [cell setBlock:^{
            [self.view bringSubviewToFront:_wayPointCV];
            
            [self.view bringSubviewToFront:_userView];
            
        }];
        return cell;
    }
}

#pragma mark UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.wayPointCV) {
        WayPointDataSource *wayData = _wayPointArr[indexPath.section];
        WayPointDataSource_WayPoints *data = wayData.waypoints[indexPath.item];
        CGFloat imageHeight =[[data.photo_info objectForKey:@"h"] floatValue];
        CGFloat imageWidth =[[data.photo_info objectForKey:@"w"] floatValue];
        
        NSString *str = data.text;
        
        NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:12]};
        CGRect rect = [str boundingRectWithSize:CGSizeMake(self.wayPointCV.frame.size.width, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        if (imageWidth == 0) {
            imageWidth = 1;
        }
        return CGSizeMake(self.view.frame.size.width - 20 , (self.view.frame.size.width - 20) * imageHeight / imageWidth + rect.size.height + 50);
    }else
    {
        return CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
    }
    
    
    
}

#pragma mark - Hide MB


- (void)hudWasHidden:(MBProgressHUD *)hud
{
    
    [_progress removeFromSuperview];
    [_progress release];
    _progress  = nil;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBarHidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
